<script setup>
import { RouterLink, RouterView } from "vue-router";
import { ref, reactive, computed, onMounted, watch, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useOrganisationUserStore } from "../stores/organisationUser";
import { useAppUserStore } from "../stores/appUser";
import { usePluginConfigStore } from "../stores/pluginConfig";
import Logo from "@/components/mains/Logo.vue";

const store = useOrganisationUserStore();
const appUserStore = useAppUserStore();
const pluginConfigStore = usePluginConfigStore();
const router = useRouter();
const route = useRoute();
// do not use same name with ref
const form = reactive({
  appid: "",
  username: "admin",
  password: "admin12345",
});
const loading = ref(false);
const isLoginWithPlugin = ref(false);
const appIds = ref([]);
const customizationVerifyExtensions = ref([]);

const pluginLoginForm = reactive({
  pluginId: "",
  accessToken: "",
});

const thirdPartToken = computed(() => route.query.access_token);
const thirdPartAppid = computed(() => route.query.appid);
const pluginId = computed(() => route.query.pluginId);

const onSubmit = async (auto) => {
  loading.value = true;
  try {
    const res = auto
      ? await store.autoLogin({
          access_token: thirdPartToken.value,
          appid: thirdPartAppid.value,
          pluginId: pluginId.value,
        })
      : await store.login({
          appid: form.appid,
          username: form.username,
          password: form.password,
        });
    appUserStore.setCurrentUser(res.userInfo, true);

    if (router.currentRoute.value.redirectedFrom) {
      // redirectedFrom 是解析出的路由地址，就像导航守卫中的 to和 from
      router.push(router.currentRoute.value.redirectedFrom);
    } else {
      if (res.userInfo.isManager) {
        router.push({
          path: "/home",
          // query: {
          //   ...route.query,
          // },
        });
      } else {
        router.push({
          path: "/WorkTask/MyTasks",
        });
      }
    }
  } catch (error) {
    loading.value = false;
  }
  loading.value = false;
};

const getAllAppIds = async () => {
  appIds.value = (await store.getAllAppIds()).filter(
    (item) => item != "" && item != null
  );
};

const loadCustomizationVerifyExtensions = async () => {
  customizationVerifyExtensions.value = [
    { pluginId: "", name: "---全部---" },
    ...(await pluginConfigStore.getCustomizationVerifyExtensions()),
  ];
};

/**
 * 通过插件登录（本质上还是走 autologin，只是增加了可选指定插件id的选项，同时表单可视化易编辑）
 */
const loginWithPlugin = async () => {
  appUserStore.setThirdpartToken(pluginLoginForm.accessToken);
  await nextTick();
  router.push({
    path: "/login",
    query: {
      access_token: pluginLoginForm.accessToken,
      appid: form.appid,
      pluginId: pluginLoginForm.pluginId,
      t: new Date().getTime(),
    },
  });
};

watch(
  () => route,
  () => {
    load();
  },
  { deep: true }
);

const load = () => {
  getAllAppIds();
  loadCustomizationVerifyExtensions();

  if (thirdPartToken.value && thirdPartToken.value.length > 0) {
    appUserStore.setThirdpartToken(thirdPartToken.value);
    onSubmit(true);
  }
};

onMounted(() => {
  load();
});
</script>

<template>
  <el-container class="layout-container-main">
    <el-header height="60px">
      <el-menu class="el-menu-demo" mode="horizontal" :ellipsis="false">
        <el-menu-item>
          <Logo />
        </el-menu-item>
        <el-menu-item>登录</el-menu-item>
        <el-menu-item>联系我们</el-menu-item>
      </el-menu>
    </el-header>

    <el-container>
      <el-main>
        <img
          style="width: 100%; height: 100%"
          src="https://cn.bing.com/th?id=OHR.LakeBledSnow_ZH-CN4118056813_1920x1080.jpg&rf=LaDigue_1920x1080.jpg"
          alt="Element logo"
        />
      </el-main>
      <el-aside width="500px">
        <div>
          <Logo />
          <br />
          <br />
        </div>
        <el-form
          :model="form"
          label-width="auto"
          style="max-width: 400px"
          v-loading="loading"
        >
          <el-form-item>
            <el-select
              v-model="form.appid"
              filterable
              allow-create
              default-first-option
              :reserve-keyword="false"
              placeholder="选择或者输入appid"
              prefix-icon="House"
            >
              <el-option
                v-for="item in appIds"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <template v-if="!isLoginWithPlugin">
            <el-form-item>
              <el-input
                v-model="form.username"
                clearable
                prefix-icon="User"
                placeholder="username"
              />
            </el-form-item>
            <el-form-item>
              <el-input
                v-model="form.password"
                type="password"
                clearable
                prefix-icon="Lock"
                placeholder="password"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="onSubmit(false)"
                style="width: 100%"
                >登 录</el-button
              >
            </el-form-item>
          </template>

          <template v-if="isLoginWithPlugin">
            <el-form-item>
              <el-select
                v-model="pluginLoginForm.pluginId"
                filterable
                default-first-option
                :reserve-keyword="false"
                placeholder="选择插件（不选将逐一尝试）"
                prefix-icon="House"
              >
                <el-option
                  v-for="item in customizationVerifyExtensions"
                  :key="item.pluginId"
                  :label="item.name"
                  :value="item.pluginId"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input
                v-model="pluginLoginForm.accessToken"
                style="width: 100%"
                :rows="5"
                type="textarea"
                placeholder="请输入 AccessToken"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="loginWithPlugin()"
                style="width: 100%"
                >登 录</el-button
              >
            </el-form-item>
          </template>

          <el-form-item>
            <el-link
              type="primary"
              v-if="!isLoginWithPlugin"
              @click="isLoginWithPlugin = true"
              >>>使用插件登录
            </el-link>
            <el-link type="primary" v-else @click="isLoginWithPlugin = false"
              >>>使用账号密码登录
            </el-link>
          </el-form-item>
        </el-form>
      </el-aside>
    </el-container>
    <el-footer>
      <div style="text-align: center">
        <span>Copyright © 2022-2023</span> |
        <span>
          ICP备案号：
          <a href="http://beian.miit.gov.cn/">粤ICP备2024356317号-1</a>
        </span>
      </div>
    </el-footer>
  </el-container>
</template>

<style scoped>
.layout-container-main {
  width: 100vw;
}
.layout-container-main .el-header {
  color: var(--el-text-color-primary);
  padding: 0px;
}
.layout-container-main .el-aside {
  color: var(--el-text-color-primary);
  padding: 50px;
}

.layout-container-main .el-main {
  padding: 20px;
  overflow-y: hidden;
  width: calc(100vw - 400px);
  height: calc(100vh - 140px);
}

.el-menu--horizontal > .el-menu-item:nth-child(2) {
  margin-right: auto;
}
</style>
